import {
	STATIC_URL
} from '@/config'

import {
	TOKEN
} from '@/config/constant'

import {
	getCache
} from './storage.js'

import { $msg } from './msg.js'

export function $copy(data) {
	uni.setClipboardData({ data });
}

export function $setTitle(title) {
	uni.setNavigationBarTitle({
		title
	})
}

/**
 * 转换对象为queryString
 * 将{a:1,b:2}=>a=1&b=2
 * @param {Object} params
 */
export function convertObj2Str(params) {
	if (!params) return ''
	return Object.keys(params).map(key => [key, params[key]].join('=')).join('&')
}

/**
 * 验证是否登录
 */
export let $checkLogin = () => Boolean(getCache(TOKEN))

/**
 * 是否是空字符串
 * @param {Object} str
 */
export let isEmptyStr = (str) => !str || !str.trim()

/**
 * 是否是空数组
 * @param {Arrary} arr
 */
export let isEmptyArr = (arr) => !arr || !arr.length

/**
 * 是否是空对象
 * @param {Arrary} arr
 */
export let isEmptyObj = (obj) => !Object.keys(obj).length

/**
 *   从对象或者对象数组中择出你要的字段，如将form瘦身
 * 
	 let obj = { a: 1, b: 2, c: 3, d: 4 }
	 pick(obj, ['b', 'd'])  // {  b: 2, d: 4 }
	 
	 let arr1 = [
		 { a: 1, b: 2, c: 3, d: 4 }, 
		 { a: 11, b: 22, c: 33, d: 44 }, 
		 { a: 111, b: 222, c: 333, d: 444 }
	 ]
	 pick(arr1, ['b', 'c']) // [{  b: 2, c: 3 },{  b: 22, c: 33 }, ...]
 */
export function pick(obj, keys) {
	if (!obj) return;
	if (Array.isArray(obj)) return obj.map(r => pickObj(r, keys))
	return pickObj(obj, keys)
}

function pickObj(obj, keys) {
	return keys.reduce((o, r) => {
		let val = obj[r];
		isNotUndef(val) && (o[r] = val)
		return o
	}, {})
}

export let isUndef = obj => obj === undefined
export let isNotUndef = obj => obj !== undefined

/**
 * last([1,2,3])
 * last('123123')
 * 
 * 取数组或者字符串的最后一个值
 */
export let last = input => input[input.length - 1]

/**
 * 算出数组的某字段的和，如未读数量
 * let arr = [{ count: 111 }, { count: 444 }]
 * sum(arr, r => r.count));
 */
export let sum = (arr, fn) => arr.reduce((t, r) => t + fn(r), 0)

/**
 * 截取字符串  如张三丰发发发 => 张三...
 */
export function limitStr(str, limit = 20) {
	if (!str) return ''
	if (str.length <= limit) return str
	return str.substr(0, limit) + '...'
}

/**
 * 按条件合并数组
 * 将[{id:1,name:'ace'},{id:2,name:'zzz'}]和[{id:1,age:20}]
 * 合并成
 * [[{id:1,name:'ace',age:20},{id:2,name:'zzz'}]]
 * @param {Array} a
 * @param {Array} b
 * @param {Function} fn
 */
export function $merge(a, b, fn) {
	return a.map(r => {
		let bb = b.find(rr => fn(r, rr)) || {}
		return {
			...r,
			...bb
		}
	})
}

/**
 * 比较两个数据是否相等，支持基本类型和引用类型
 */
export function eq(a, b) {
	if (a === b) return true
	if (typeof a !== 'object') return false
	if (toString(a) !== toString(b)) return false
	return Object.keys(a).every(k => eq(a[k], b[k]))
}
